package com.kgc.scd.controller;

import com.kgc.scd.annotation.RequestPermission;
import com.kgc.scd.annotation.RequestUser;
import com.kgc.scd.bean.*;
import com.kgc.scd.service.PlaceOrderFeignService;
import com.kgc.scd.service.PlaceOrderService;
import com.kgc.scd.service.SubmitOrderService;
import com.kgc.scd.service.UserService;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import com.kgc.scd.util.UserAnno;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2022/6/13.
 * <p>
 * Author     : 98730
 * <p>
 * Description: 下单操作入口
 */
@Slf4j
@RestController
public class PlaceOrderController {

    @Autowired
    private PlaceOrderService placeOrderService;

    @Autowired
    private UserService userService;

    @Autowired
    private PlaceOrderFeignService placeOrderFeignService;

    @Autowired
    private SubmitOrderService submitOrderService;

    @PostMapping("/PlaceOneOrder")
    public RequestResult<Map<String,Object>> PlaceOneOrder(@RequestParam String orderId,
                                            @RequestParam(required = false) Integer innerId,
                                            @RequestParam(required = false) String addrId,
                                            @RequestBody UserAnno userAnno){
        Map<String,Object> resultMap = new HashMap<>();
        // 判断用户
        User user = userService.selectUserById(userAnno.getUserId());
        if (addrId == null || addrId == ""){
            if (StringUtils.isEmpty(user.getUserAddrId())) {
                resultMap.put("result","地址不能为空！");
                return ResultBuildUtil.fail(resultMap);
            } else {
                addrId = user.getUserAddrId();
            }
        }

        // 判断是否使用优惠券
        Coupon coupon = new Coupon();
        if (innerId != null) {
            // 校验优惠券是否在有效期，失效返回null
            coupon = placeOrderFeignService.updateUserCouponIsLate(userAnno.getUserId(), innerId);
            if(coupon == null) {
                resultMap.put("result","优惠券不可用！");
                return ResultBuildUtil.fail(resultMap);
            }
            // TODO 优惠券可用，将该优惠券状态改为已使用
            placeOrderFeignService.changeUserCouponStatus(innerId);
        }

        // 更新order表中的数据
        double sumPrice = 0;
        double postage = 10;

        // 根据订单号，查询订单计算总价
        List<OrderItemResult> orderItemResults = submitOrderService.selectOrderItemResult(orderId);
        for (OrderItemResult o : orderItemResults) {
            sumPrice += o.getProPrice() * o.getItemNum();
        }

        // 计算使用优惠券金额
        if (innerId != null) {
            if (coupon.getCouType() == 1) {
                // 为折扣券
                sumPrice *= coupon.getCouDiscount().doubleValue();
            } else if (coupon.getCouType() == 0) {
                sumPrice -= coupon.getCouSub();
            }
        }

        log.info("判断会员前，商品总价为：{}", sumPrice);

        // TODO 进行用户会员是否到期判断
        // 判断用户会员等级
        List<Vip> vips = userService.selectVipLevelByUserId(userAnno.getUserId());
        if (!vips.isEmpty()) {
            Vip vip = vips.get(0);
            // 根据会员等级，修改订单金额（根据使用优惠券后的金额进行计算）
            if (vip.getVipLevel() != 0) {
                // 说明为会员，邮费变为0
                postage = 0;
                if (vip.getVipLevel() == 3 || vip.getVipLevel() == 4) {
                    sumPrice *= 0.95;
                } else if (vip.getVipLevel() == 5 || vip.getVipLevel() == 6) {
                    sumPrice *= 0.9;
                }
            }
        }
        // 总价增加运费
        sumPrice += postage;

        Order newOrder = Order.builder().orderAddrid(addrId)
            .orderId(orderId)
            .orderPrice(sumPrice).build();
        if (innerId != null) {
            newOrder.setOrderCouid(coupon.getCouId());
        }

        placeOrderService.modOrderDetail(newOrder);
        List<OrderItem> orderItemList =  placeOrderService.queryOrderItemByOrderId(orderId);

        for (OrderItem orderItem : orderItemList){
            // 扣减库存之前的库存
            Integer stock = placeOrderService.queryProductByProId(orderItem.getItemProid()).getProStock();
            stock -= orderItem.getItemNum();

            if (stock > 0) {
                Product product = Product.builder().proId(orderItem.getItemProid())
                                .proStock(stock)
                                .build();
                placeOrderService.modProductDetail(product);
            } else {
                resultMap.put("result","商品库存不足!");
                return ResultBuildUtil.fail(resultMap);
            }
        }

        resultMap.put("result",true);
        resultMap.put("order",orderId);
        resultMap.put("sumPrice",sumPrice);
        resultMap.put("postage",postage);
        return ResultBuildUtil.success(resultMap);
    }


    // 秒杀下单
    @PostMapping("/PlaceOneSeckillOrder")
    public RequestResult<Map<String,Object>> PlaceOneSeckillOrder(@RequestParam String orderId,
                                                      @RequestParam(required = false) String addrId,
                                                      @RequestBody UserAnno userAnno){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = placeOrderService.queryOrder(orderId);
        if (order.getOrderPrice() != 0.00){
            resultMap.put("result","您已下单，请勿重复购买！");
            return ResultBuildUtil.fail(resultMap);
        }

        // 判断用户
        User user = userService.selectUserById(userAnno.getUserId());
        if (addrId == null || addrId == ""){
            if (StringUtils.isEmpty(user.getUserAddrId())) {
                resultMap.put("result","地址不能为空！");
                return ResultBuildUtil.fail(resultMap);
            } else {
                addrId = user.getUserAddrId();
            }
        }
        // 更新order表中的数据
        double sumPrice = 0;
        double postage = 10;

        // 根据订单号，查询订单计算总价
        List<SelectSeckillOrder> seckillOrders = submitOrderService.selectSeckillOrderResult(orderId);
        log.info("查询订单计算总价：{}",seckillOrders);
        for (SelectSeckillOrder seckillOrder : seckillOrders) {
            sumPrice += seckillOrder.getSeckillPrice() * seckillOrder.getItemNum();
        }

        // 总价增加运费
        sumPrice += postage;

        Order newOrder = Order.builder().orderAddrid(addrId)
                .orderId(orderId)
                .orderPrice(sumPrice).build();

        placeOrderService.modOrderDetail(newOrder);
        List<OrderItem> orderItemList =  placeOrderService.queryOrderItemByOrderId(orderId);

        for (OrderItem orderItem : orderItemList){
            // 扣减库存之前的库存
            Seckill seckill = placeOrderService.querySeckillProductByProId(orderItem.getItemProid());
            Integer stock = seckill.getSeckillProstock();
            stock -= orderItem.getItemNum();

            if (stock > 0) {
                Seckill seckill1 = Seckill.builder().seckillProid(orderItem.getItemProid())
                        .seckillProstock(stock)
                        .seckillPrice(seckill.getSeckillPrice())
                        .build();
                placeOrderService.modSeckillDetail(seckill1);
            } else {
                resultMap.put("result","商品库存不足!");
                return ResultBuildUtil.fail(resultMap);
            }
        }
        resultMap.put("result",true);
        resultMap.put("order",orderId);
        resultMap.put("sumPrice",sumPrice);
        resultMap.put("postage",postage);
        return ResultBuildUtil.success(resultMap);
    }
}
